package nl.hanze.db.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;

import nl.hanze.db.def.TableDefinition;

public class TableDataIO_Unsorted extends TableDataIO {
	public TableDataIO_Unsorted(TableDefinition def) throws Exception {
		super(def);
	}

	/**** OPGAVE 3e ***/
	@Override
	public long add(String[] record) throws Exception {
		long s = System.currentTimeMillis();

		int pkpos = pkValLocation(record, def.getColPosition(def.getPK()));
		if (pkpos != -1)
			throw new Exception("Primary key already in table");

		FileWriter fw = new FileWriter(BaseIO.getInitDir() + File.separator
				+ def.getTableName() + ".tbl", true);
		StringBuffer temp = new StringBuffer();
		Integer[] size = def.getSizes();
		if (size.length != record.length) {
			fw.close();
			throw new Exception("Malformed record");
		}

		for(int i = 0; i < record.length; i++) {
			temp.append(appendSpaces(record[i], size[i]));
			if (i != record.length - 1) {
				temp.append("#");
			}
		}
		temp.append("\r\n");

		fw.write(temp.toString());
		fw.close();
		long e = System.currentTimeMillis();
		return e - s;
	}

	/*** OPGAVE 3g ***/
	@Override
	public long delete(String colname, String value) throws Exception {
		long s = System.currentTimeMillis();
		
		String[] colNames = def.getColnames();
		boolean foundColname = false;
		int colPos = 0;
		for(int i = 0; i < colNames.length; i++) {
			if(colname.equals(colNames[i])) {
				colPos = i;
				foundColname = true;
			}
		}
		
		File tmpfile = new File(BaseIO.getInitDir() + File.separator + def.getTableName() + "_tmp.tbl");
		FileWriter fw = new FileWriter(tmpfile, true);
		
		for(int i = 0; i < numOfRecords(); i++) {
			raf.seek(i * recordLength());
			String sLine = raf.readLine();
			String[] record = sLine.split("#");
			for (int j = 0; j < record.length; j++) {
				record[j] = stripSpaces(record[j]);
			}
			String key = record[colPos];
			if(!key.equals(value)) {
				StringBuffer temp = new StringBuffer();
				Integer[] size = def.getSizes();
				if (size.length != record.length) {
					fw.close();
					throw new Exception("Malformed record");
				}

				for(int j = 0; j < record.length; j++) {
					temp.append(appendSpaces(record[j], size[j]));
					if (j != record.length - 1) {
						temp.append("#");
					}
				}
				temp.append("\r\n");
				fw.write(temp.toString());
			}
		}

		File oldfile = new File(BaseIO.getInitDir() + File.separator + def.getTableName() + ".tbl");
		BaseIO.closeFile(def.getTableName() + ".tbl");
		raf.close();
		fw.close();
		System.out.println("deleted old file: " + oldfile.delete());
		System.out.println("rename: " + tmpfile.renameTo(new File(BaseIO.getInitDir() + File.separator
				+ def.getTableName() + ".tbl")));
		
		BaseIO.openFile(def.getTableName() + ".tbl");
		raf = BaseIO.getFile(def.getTableName() + ".tbl");
		long e = System.currentTimeMillis();
		return e - s;
	}

	/*** OPGAVE 3h ***/
	@Override
	public long update(String[] record) throws Exception {	
		long s = System.currentTimeMillis();
		
		StringBuffer temp = new StringBuffer();
		Integer[] size = def.getSizes();
		if (size.length != record.length) {
			throw new Exception("Malformed record");
		}

		for (int i = 0; i < record.length; i++) {
			temp.append(appendSpaces(record[i], size[i]));
			if (i != record.length - 1) {
				temp.append("#");
			}
		}
		temp.append("\r\n");

		for(int i = 0; i < numOfRecords(); i++) {
			String pk = recordAt(i)[0];
			
			if(pk.equals(record[0])) {
				raf.seek(i * recordLength());
				raf.write(temp.toString().getBytes());
			}
		}
		long e = System.currentTimeMillis();
		return e - s;
	}

	/*** OPGAVE 3i ***/
	@Override
	public long search(String colname, String value, ArrayList<String[]> result) throws Exception {
		long s = System.currentTimeMillis();
		
		String[] colNames = def.getColnames();
		boolean foundColname = false;
		int colPos = 0;
		for(int i = 0; i < colNames.length && !foundColname; i++) {
			if(colname.equals(colNames[i])) {
				colPos = i;
				foundColname = true;
			}
		}
		
		for(int i = 0; i < numOfRecords(); i++) {
			String[] record = recordAt(i);
			String key = record[colPos];
			if(key.equals(value)) {
				result.add(record);
			}
		}
		long e = System.currentTimeMillis();
		return e - s;
	}

	/*** OPGAVE 3c ***/
	private int pkValLocation(String[] record, int col) throws Exception {
		String pkval = record[col];
		boolean found = false;
		int i = 0;
		for (i = 0; i < numOfRecords() && !found; i++)
			found = recordAt(i)[col].equals(pkval);

		return found ? i - 1 : -1;
	}

}